package top.yzlin.dblock.tools;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Tools {

    private static MessageDigest md;

    static {
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static String getUniqueId() {
        return strToMD5(String.valueOf(System.currentTimeMillis()) + Math.random());
    }

    public static String strToMD5(String str) {
        StringBuilder num = new StringBuilder();
        synchronized (md) {
            md.update(str.getBytes(StandardCharsets.UTF_8));
            num.append(new BigInteger(1, md.digest()).toString(16));
        }
        while (num.length() < 32) {
            num.insert(0, "0");
        }
        return num.toString();
    }
}
